package com.hqyj.springCloudWeb.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//通过拦截器来实现页面的碎片组装
@Component//注册拦截器
public class RequestViewMappingInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.debug("==== Pre HandlerInterceptor");
        return HandlerInterceptor.super.preHandle(request,response,handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.debug("==== Post HandlerInterceptor");
        //接口不需要处理，转发不需要处理，重定向也不需要处理
        if(modelAndView == null ||
           modelAndView.getViewName().toLowerCase().startsWith("redirect") ||
           modelAndView.getViewName().toLowerCase().startsWith("forward")){
            return;
        }

        //获取请求的路径
        String path = request.getServletPath();
        LOGGER.debug(request.getServletPath() + "--" + request.getRequestURI());
        String template = (String) modelAndView.getModelMap().getAttribute("page");
        //当文件上传的时候如果用户设置了路径那么就以用户设置的路径为准，没有设置的话再以默认为准
        if(StringUtils.isBlank(template) && StringUtils.isNotBlank(path)){
            //如果路径是以/开始的就去掉第一位
            if(path.startsWith("/")){
                path = path.substring(1,path.length());
            }
            modelAndView.getModelMap().addAttribute("page",path);
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.debug("==== After HandlerInterceptor");
    }
}
